package com.bci.pwtz.controller.app;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.bci.pwtz.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.remote.BaseRequest;
import com.bci.pwtz.common.remote.BaseResponse;
import com.bci.pwtz.common.remote.ObjResponse;
import com.bci.pwtz.common.remote.ReturnCode;
import com.bci.pwtz.common.remote.req.CreateRandomCodeReq;
import com.bci.pwtz.common.remote.req.GetCodeReq;
import com.bci.pwtz.common.remote.req.LoginReq;
import com.bci.pwtz.common.remote.req.PasswordReq;
import com.bci.pwtz.common.remote.req.RandomCodeReq;
import com.bci.pwtz.common.remote.req.RegisterReq;
import com.bci.pwtz.common.remote.req.ValidateCodeReq;
import com.bci.pwtz.common.remote.resp.GetCodeResp;
import com.bci.pwtz.common.remote.resp.LoginResp;
import com.bci.pwtz.common.remote.resp.UserListResp;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.common.util.SHA256Cryptor;
import com.bci.pwtz.controller.AbstractController;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.exception.VerifyCodeIsBusyException;
import com.bci.pwtz.exception.VisitCountIsOverTheLimitException;
import com.bci.pwtz.mysql.dao.CompanyUserRoleMapper;
import com.bci.pwtz.mysql.model.Company;
import com.bci.pwtz.mysql.model.CompanyRole;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.CompanyUserRole;
import com.bci.pwtz.mysql.model.RandomCode;
import com.bci.pwtz.mysql.model.SmsSendLog;
import com.bci.pwtz.mysql.model.UserCompanyRef;
import com.bci.pwtz.service.sms.SendSmsService;



/**
 * 用户控制器controller <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 包含以下功能 <br/>
 * 登陆 <br/>
 * 
 * <PRE>
 *      /user/${actionName}
 * </PRE>
 * <p>
 */
@Controller
@RequestMapping("/api/user")
public class CompanyUserAppController extends AbstractController
{
    @Autowired
    private CompanyUserService     companyUserService;
    
    @Autowired
    private CompanyService     companyService;
    
    @Autowired
    private VerifyCodeService     verifyCodeService;
    
    @Autowired
    private CompanyRoleService     companyRoleService;
    
    @Autowired
    private SendSmsService     sendSmsService;
    @Autowired
    private SmsSendLogService     smsSendLogService;
    @Autowired
    private UserCompanyRefService userCompanyRefService;
    @Autowired
    private CompanyUserRoleMapper companyUserRoleMapper;
    @Autowired
    private LoginDeviceCodeService loginDeviceCodeService;
    /**
     * 
     * 登录 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: tonic<br/>
     * <p>Date: 2014-9-18-下午2:46:43<br/>
     * <p>
     * @param req
     * @return   
     *
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public LoginResp login(HttpServletRequest request)
    {
        LoginReq req = null;
        LoginResp resp = new LoginResp();
        try
        {
            req= (LoginReq)getJsonToObj(request,LoginReq.class);
            if(req==null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空");
                return resp;
            }
            if( req.getMobile()==null || req.getPassword()==null ){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(req.getTimestamp()==null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("时间戳为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String pwd = req.getPassword();
            String tel = req.getMobile();
            String devicecode=req.getDeviceCode();
            System.out.println("login: tel="+tel+"|pwd="+pwd);
            CompanyUser user = companyUserService.findUserInfo(tel,pwd);
            if(!loginDeviceCodeService.isThisDevice(devicecode,tel)){
                resp.setReturnCode(ReturnCode.OTHER_DEVICE);
                resp.setReturnMsg("该账号已绑定其他设备");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if (null != user)
            {
                resp.setObj(user);
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("登录成功");
                resp.setTimestamp(req.getTimestamp());
                String token = UUID.randomUUID().toString();
                resp.setToken(token);
                Long userId = user.getCompanyUserId();
                if(userId!=null){
                    System.out.println("login="+token+userId+"|"+PwtzUtils.getMinuteAfter(new Date(),PwtzConstants.TOKEN_VAILD));
                    PwtzConstants.TOKEN_MAP.put(token+userId, PwtzUtils.getMinuteAfter(new Date(),PwtzConstants.TOKEN_VAILD));
                }
                if(req.getDeviceId()!=null){
                    //删除数据库所有DeviceId
                    companyUserService.clearDeviceId(req.getDeviceId()); 
                    user.setDeviceId(req.getDeviceId());
                    companyUserService.update(user);
                }
            }
            else
            {
                resp.setReturnCode(ReturnCode.ACCOUNT_PWD_NOT_MATCH);
                resp.setReturnMsg("用户名或密码不匹配");
                resp.setTimestamp(req.getTimestamp());
            }

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }

        return resp;
    }
    
    /**
     * 
     * 登出 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: tonic<br/>
     * <p>Date: 2014-9-24-下午2:22:31<br/>
     * <p>
     * @param request
     * @return   
     *
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse logout(HttpServletRequest request)
    {
        BaseRequest req = null;
        BaseResponse resp = new BaseResponse();
        try
        {
            req= getJsonToObj(request,BaseRequest.class);
            if(req==null ){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空");
                return resp;
            }
            if(req.getTimestamp()==null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("时间戳为空");
                resp.setTimestamp(req.getTimestamp());
                return resp; 
            }
            if(req.getUserId()==null)
            {
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(req.getToken()!=null){
                if(PwtzConstants.TOKEN_MAP.containsKey(req.getToken()+req.getUserId())){
                    PwtzConstants.TOKEN_MAP.remove(req.getToken()+req.getUserId());
                    resp.setReturnCode(ReturnCode.SUCCESS);
                    resp.setReturnMsg("登出成功");
                    resp.setTimestamp(req.getTimestamp());
                }else{
                    resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                    resp.setReturnMsg("票据无效");
                    resp.setTimestamp(req.getTimestamp());
                }
            }else{
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }

        return resp;
    }
    
    /**
     * 
     * 获取验证码 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: tonic<br/>
     * <p>Date: 2014-9-24-下午2:22:48<br/>
     * <p>
     * @param request
     * @return   
     *
     */
    @RequestMapping(value = "/getcode", method = RequestMethod.POST)
    @ResponseBody
    public GetCodeResp getCode(HttpServletRequest request)
    {
        GetCodeReq req = null;
        GetCodeResp resp = new GetCodeResp();
        try
        {
            req= (GetCodeReq)getJsonToObj(request,GetCodeReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空");
                return resp;
            }
            if(StringUtils.isBlank(req.getTimestamp())){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("时间戳为空");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getMobile())){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp; 
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String mobile = req.getMobile();
            int ret = companyUserService.selectCountByMobile(mobile);
            if(req.getType()==1){
                if(ret>0){
                    resp.setReturnCode(ReturnCode.HAS_MOBILE);
                    resp.setReturnMsg("手机号码已注册");
                    resp.setTimestamp(req.getTimestamp());
                    return resp;
                }
            }else  if(req.getType()==2){
                if(ret==0){
                    resp.setReturnCode(ReturnCode.HAS_NOT_MOBILE);
                    resp.setReturnMsg("手机号码不存在");
                    resp.setTimestamp(req.getTimestamp());
                    return resp;
                }
            }
            String code = verifyCodeService.getCode(mobile,req.getType());
            if (StringUtils.isNotEmpty(code))
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("获取验证码成功");
                resp.setCode(code);
                resp.setTimestamp(req.getTimestamp());
            }
            else
            {
                resp.setReturnCode(ReturnCode.ACCOUNT_PWD_NOT_MATCH);
                resp.setReturnMsg("获取验证码失败");
                resp.setTimestamp(req.getTimestamp());
            }

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (VerifyCodeIsBusyException e)
        {
            resp.setReturnCode(ReturnCode.VERIFY_CODE_IS_BUSY);
            resp.setReturnMsg("获取验证码太过频繁");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (VisitCountIsOverTheLimitException e)
        {
            resp.setReturnCode(ReturnCode.OVER_THE_LIMIT);
            resp.setReturnMsg("当日获取验证码次数超过限制");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    
    /**
     * 
     * 同步用户信息 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: tonic<br/>
     * <p>Date: 2014-9-24-下午2:23:04<br/>
     * <p>
     * @param request
     * @return   
     *
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public UserListResp list(HttpServletRequest request)
    {
        BaseRequest req = null;
        UserListResp resp = new UserListResp();
        try
        {
            req= (BaseRequest)getJsonToObj(request,BaseRequest.class);
            if(req==null || StringUtils.isBlank(req.getTimestamp()) || req.getUserId()==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId())){
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            CompanyUser user = companyUserService.load(req.getUserId());
            if (null != user)
            {
                resp.setObj(user);
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("同步用户信息成功");
                resp.setTimestamp(req.getTimestamp());
                Long userId = user.getCompanyUserId();
                //获取当前用户加入的公司和创建的公司
                List<Company> list =companyService.findCompanyByUserId(userId);
                if(list!=null && list.size()>0){
                    resp.setCompanyList(list);
                }
                List<CompanyRole> roleList =companyRoleService.findCompanyRoleByUserId(userId);
                if(roleList!=null && roleList.size()>0){
                    resp.setRoleList(roleList);
                }
                List<UserCompanyRef> userCompanyList=userCompanyRefService.findUserCompanyRefList(userId);
                if(userCompanyList!=null&&userCompanyList.size()>0){
                    resp.setUserCompanyRefList(userCompanyList);
                }
                List<CompanyUserRole> userRoleList=companyUserRoleMapper.selectRoleByUserId(userId);
                if(userRoleList!=null&&userRoleList.size()>0){
                    resp.setCompanyUserRoleList(userRoleList);
                }
            }
            else
            {
                resp.setReturnCode(ReturnCode.ACCOUNT_PWD_NOT_MATCH);
                resp.setReturnMsg("该用户不存在");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    
    /**
     * 
     * 登录 <br/>
     * <p>Description: TODO(详细描述) 
     * <br/>
     * <p>Author: tonic<br/>
     * <p>Date: 2014-9-18-下午2:46:43<br/>
     * <p>
     * @param req
     * @return   
     *
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ObjResponse<CompanyUser> register(HttpServletRequest request)
    {
        RegisterReq req = null;
        ObjResponse<CompanyUser> resp = new ObjResponse<CompanyUser> ();
        try
        {
            req= (RegisterReq)getJsonToObj(request,RegisterReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(req.getMobile()==null || req.getPassword()==null || req.getTimestamp()==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String pwd = req.getPassword();
            String mobile = req.getMobile();
            String loginName = req.getLoginName();
            String rCode = req.getRandomCode();
            int ret = companyUserService.selectCountByMobile(mobile);
            if(ret>0){
                resp.setReturnCode(ReturnCode.HAS_MOBILE);
                resp.setReturnMsg("电话号码已注册");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            ret = companyUserService.selectCountByName(loginName);
            if(ret>0){
                resp.setReturnCode(ReturnCode.HAS_NAME);
                resp.setReturnMsg("用户名已注册");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            RandomCode randomCode =null;
            CompanyUser user = new CompanyUser();
            user.setMobile(mobile);
            user.setLoginName(loginName);
            user.setUserName(req.getUserName());
            user.setLoginPwd(pwd);
            if(StringUtils.isNotEmpty(rCode)){
                randomCode = companyUserService.selectRandomCode(rCode);
                if(randomCode==null){
                    resp.setReturnCode(ReturnCode.RANDOM_CODE_INVALID);
                    resp.setReturnMsg("邀请码无效");
                    resp.setTimestamp(req.getTimestamp());
                    return resp;
                }else{
                    if(randomCode.getCompanyId()!=null){
                        user.setLastCompanyId(randomCode.getCompanyId());
                        user = companyUserService.register(user);
                    }else{
                        user = companyUserService.register(user);
                    }
                    if(randomCode.getCompanyId()!=null){
                        UserCompanyRef ref = new UserCompanyRef();
                        ref.setCompanyId(randomCode.getCompanyId());
                        ref.setCompanyUserId(user.getCompanyUserId());
                        companyUserService.addUserCompanyRef(ref);
                    }
                    if(randomCode.getCompanyId()!=null){
                        CompanyUserRole ref = new CompanyUserRole();
                        ref.setCompanyRoleId(randomCode.getCompanyRoleId());
                        ref.setCompanyUserId(user.getCompanyUserId());
                        companyUserService.addCompanyUserRole(ref);
                    }
                }
            }else{
                user = companyUserService.register(user);
            }
            if (null != user)
            {
                resp.setObj(user);
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("注册成功");
                resp.setTimestamp(req.getTimestamp());
            }
            else
            {
                resp.setReturnCode(ReturnCode.ACCOUNT_PWD_NOT_MATCH);
                resp.setReturnMsg("注册失败");
                resp.setTimestamp(req.getTimestamp());
            }

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }

        return resp;
    }
    
    @RequestMapping(value = "/createrandomcode", method = RequestMethod.POST)
    @ResponseBody
    public GetCodeResp createRandomCode(HttpServletRequest request)
    {
        CreateRandomCodeReq req = null;
        GetCodeResp resp = new GetCodeResp();
        try
        {
            req= (CreateRandomCodeReq)getJsonToObj(request,CreateRandomCodeReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getTimestamp()) || req.getCompanyId()<=0 ||req.getCompanyRoleId()<=0){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId())){
                resp.setReturnCode(ReturnCode.TOKEN_INVALID);
                resp.setReturnMsg("票据无效");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String code="";
            List<RandomCode> list=companyUserService.getCompanyRandomCode(req.getCompanyId());
            if(list!=null&&list.size()>0){
                code=list.get(0).getRandomCode();
                resp.setReturnCode(ReturnCode.RANDOMCODE_REOPERTION);
                resp.setReturnMsg("邀请码已创建,勿重复创建");
                resp.setCode(code);
                resp.setTimestamp(req.getTimestamp());
            }else{
                 code=companyUserService.createRandomCode(req.getCompanyId(), req.getCompanyRoleId());
                if (StringUtils.isNotEmpty(code))
                {
                    resp.setReturnCode(ReturnCode.SUCCESS);
                    resp.setReturnMsg("创建邀请码成功");
                    resp.setCode(code);
                    resp.setTimestamp(req.getTimestamp());
                }
                else
                {
                    resp.setReturnCode(ReturnCode.OTHER_ERROR);
                    resp.setReturnMsg("创建邀请码失败");
                    resp.setTimestamp(req.getTimestamp());
                }
            }
            

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    
    @RequestMapping(value = "/validatecode", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse validateCode(HttpServletRequest request)
    {
        ValidateCodeReq req = null;
        BaseResponse resp = new BaseResponse();
        try
        {
            req= (ValidateCodeReq)getJsonToObj(request,ValidateCodeReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getTimestamp()) ||StringUtils.isBlank(req.getMobile())){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;  
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String mobile = req.getMobile();
            String userName = req.getUserName();
            int ret = companyUserService.selectCountByName(userName);
            if(ret>0){
                resp.setReturnCode(ReturnCode.HAS_NAME);
                resp.setReturnMsg("用户名已注册");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            
            int result = verifyCodeService.validateCode(mobile, req.getCode());
            if (result>0)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("验证码正确");
                resp.setTimestamp(req.getTimestamp());
            }
            else
            {
                resp.setReturnCode(ReturnCode.VALIDATE_CODE_ERROR);
                resp.setReturnMsg("验证码错误");
                resp.setTimestamp(req.getTimestamp());
            }

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    
    @RequestMapping(value = "/modifypassword", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse modifyPassword(HttpServletRequest request)
    {
        PasswordReq req = null;
        BaseResponse resp = new BaseResponse();
        try
        {
            req= (PasswordReq)getJsonToObj(request,PasswordReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getPassword()) ||StringUtils.isBlank(req.getUserId()+"") ||StringUtils.isBlank(req.getOldpassword())){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            int res = companyUserService.selectCountByPassword(Long.valueOf(req.getUserId()), req.getOldpassword());
            if (res == 0){
                resp.setReturnCode(ReturnCode.ACCOUNT_PWD_NOT_MATCH);
                resp.setReturnMsg("旧密码错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            CompanyUser companyUser = new CompanyUser();
            companyUser.setCompanyUserId(req.getUserId());
            companyUser.setLoginPwd(req.getPassword());
            int result = companyUserService.update(companyUser);
            if (result>0)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("密码修改成功");
                resp.setTimestamp(req.getTimestamp());
            }
            else
            {
                resp.setReturnCode(ReturnCode.OTHER_ERROR);
                resp.setReturnMsg("密码修改失败");
                resp.setTimestamp(req.getTimestamp());
            }

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    
    @RequestMapping(value = "/forgetpassword", method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse forgetPassword(HttpServletRequest request)
    {
        PasswordReq req = null;
        BaseResponse resp = new BaseResponse();
        try
        {
            req= (PasswordReq)getJsonToObj(request,PasswordReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(StringUtils.isBlank(req.getMobile()) ||StringUtils.isBlank(req.getCode())){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            int isMobile = companyUserService.selectCountByMobile(req.getMobile());
            if (isMobile == 0){
                resp.setReturnCode(ReturnCode.HAS_NOT_MOBILE);
                resp.setReturnMsg("电话号码不存在");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            int res = verifyCodeService.validateCode(req.getMobile(), req.getCode());
            if (res == 0){
                resp.setReturnCode(ReturnCode.ACCOUNT_PWD_NOT_MATCH);
                resp.setReturnMsg("验证码错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            String newPassword = PwtzConstants.PASSWORD_KEY + PwtzUtils.getRandomNumber(6);
            //CompanyUser companyUser = new CompanyUser();
            //companyUser.setCompanyUserId(Long.valueOf(req.getCompanyUserId()));
            //companyUser.setLoginPwd(SHA256Cryptor.sha256Encrypt(newPassword));
            int result = companyUserService.updatePwdByMobile(SHA256Cryptor.sha256Encrypt(newPassword), req.getMobile());
            if (result>0&&newPassword!=null&&newPassword!="")
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("密码修改成功,你的新密码为："+newPassword.substring(newPassword.length()-6));
                resp.setTimestamp(req.getTimestamp());
                //发送短信
                String msg = MessageFormat.format(PwtzConstants.MODIFIED_PASSWORD_MSG, newPassword.substring(newPassword.length()-6));
                String smsReturn = sendSmsService.batchSend(req.getMobile().split(","), msg, null, null);
                System.out.println("0".equals(smsReturn));
                if("0".equals(smsReturn) || "1".equals(smsReturn)){
                	SmsSendLog smsSendLog = new SmsSendLog();
                	smsSendLog.setMobile(req.getMobile());
                	smsSendLog.setContent(msg);
                	smsSendLogService.add(smsSendLog);
                }
            }
            else
            {
                resp.setReturnCode(ReturnCode.OTHER_ERROR);
                resp.setReturnMsg("密码修改失败");
                resp.setTimestamp(req.getTimestamp());
            }

        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }
        return resp;
    }
    @RequestMapping(value="/getrandomcode",method=RequestMethod.POST)
    @ResponseBody
    public ObjResponse<String> getRandomCode(HttpServletRequest request){
        RandomCodeReq req = null;
        ObjResponse<String> resp = new ObjResponse<String> ();
        try
        {
            req= (RandomCodeReq)getJsonToObj(request,RandomCodeReq.class);
            if(req==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("请求为空错误");
                return resp;
            }
            if(req.getCompanyId()==null||req.getCompanyId()<=0 || req.getTimestamp()==null){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("参数错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            if(StringUtils.isBlank(req.getSecretKey()) || !validateSecretKey(req.getSecretKey(), req.getTimestamp())){
                resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
                resp.setReturnMsg("密钥错误");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
            List<RandomCode> list=companyUserService.getCompanyRandomCode(req.getCompanyId());
            if(list!=null&&list.size()>0){
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("获取邀请码成功");
                resp.setObj(list.get(0).getRandomCode());
                resp.setTimestamp(req.getTimestamp());
            }
            else
            {
                resp.setReturnCode(ReturnCode.ERROR_GET_ROMDOM_CODE);
                resp.setReturnMsg("获取邀请码失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }
        catch (PwtzDatabaseException e)
        {
            resp.setReturnCode(ReturnCode.DB_EXCEPTION);
            resp.setReturnMsg("数据库操作异常");
            resp.setTimestamp(req.getTimestamp());
        }
        catch (Exception e)
        {
            resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
            resp.setReturnMsg("系统错误");
            resp.setTimestamp(req.getTimestamp());
        }

        return resp;
    }
}